#region

using System;
using IBatisNet.DataMapper;
using Com.Pirate.Domain.Objects;
using Com.Pirate.Domain.Objects.Contracts;
using Com.Pirate.Infrastructure.Services.Contracts;

#endregion


namespace Com.Pirate.Infrastructure.Services
{
	public partial class CoreDataContext : BaseDataContext
	{
		#region?Constructors?(1)?
		
		//SqlMapperSession _session=new SqlMapperSession();

		protected CoreDataContext()
		{
		}

		#endregion?Constructors?

		#region?Methods?(2)?

		//?Protected?Methods?(1)?

		public override IDataMapper<TEntity> GetDataMapper<TEntity>()
		{
			if (typeof (TEntity) == typeof (Iuserinfo))
			{
				return (IDataMapper<TEntity>)new userinfoDataMapper();
			}

			foreach (Type t in this.GetType().Assembly.GetTypes())
            {
                if (t.BaseType != null)
                {
                    bool checkFlag = false;
                    Type tmp = t;
                    while (tmp.BaseType != null)
                    {
                        if (tmp.FullName == typeof(BaseDataMapper<TEntity>).FullName)
                        {
                            checkFlag = true;
                            break;
                        }
                        tmp = tmp.BaseType;
                    }
                    if (checkFlag)
                    {
                        foreach (var attrib in t.BaseType.GetGenericArguments())
                        {
                            if (attrib.Name == typeof(TEntity).Name)
                                return (IDataMapper<TEntity>)Activator.CreateInstance(t);

                        }
                    }
                }
            }
            throw new ArgumentException("Unknown entity type. Can't create DataMapper.");
		}

        #region Transactions Control
        public override void BeginTransaction()
        {
            (new InfrastructureFactory().GetSqlMapper()).BeginTransaction();
        }
        public override void RollBackTransaction()
        {
            (new InfrastructureFactory().GetSqlMapper()).RollBackTransaction();
        }
        public override void CommitTransaction()
        {
            (new InfrastructureFactory().GetSqlMapper()).CommitTransaction();
        }

        public override void BeginTransaction<TEntity>()
        {
            this.GetDataMapper<TEntity>().Mapper.BeginTransaction();
        }
        public override void RollBackTransaction<TEntity>()
        {
            this.GetDataMapper<TEntity>().Mapper.RollBackTransaction();
        }
        public override void CommitTransaction<TEntity>()
        {
            this.GetDataMapper<TEntity>().Mapper.CommitTransaction();
        }
        #endregion


		//?Internal?Methods?(1)?

		public static IDataContext GetDataContext()
		{
			return new CoreDataContext();
		}

		#endregion?Methods?
	}
}
